﻿#include "grid_manager.h"
#include <QPalette>
#include <QtMath>

GridManager::GridManager(QGridLayout *_gridLayout,QWidget* parent,void* handle)
    :  _gridLayout(_gridLayout), _parent(parent),_handle(handle)
{
    //默认只有一个视频
    VideoWidget *gridWidget = new VideoWidget(this);
    _gridWidgets.append(gridWidget);
    _gridLayout->addWidget(gridWidget, 0, 0);
}
//分配窗体
VideoWidget* GridManager::getGridForPeer(std::string peerId)
{
  if (_peerVideos.find(peerId) != _peerVideos.end()){
      return _peerVideos[peerId];
  }
  VideoWidget* grid = getFirstFreeGrid();
  if (!grid){
    grid = new VideoWidget(this);
    _gridWidgets.push_back(grid);
    _peerVideos[peerId] = grid;
    //增加一个
    Relayout();
  }
  return grid;
}
void GridManager::ClosePeer(std::string peerId){
  if (_peerVideos.find(peerId) != _peerVideos.end())
  {
    closeVideo(_peerVideos[peerId]);
    _peerVideos.erase(peerId);
    Relayout();
  }
}
void GridManager::reset(){
  for (VideoWidget *gridWidget : _gridWidgets){
    gridWidget->reset();
  }
  _peerVideos.clear();
}

void GridManager::showWindow(VideoWidget* video,bool show){
  for (int i = 0; i < _gridWidgets.size(); ++i){
    VideoWidget *gridWidget = _gridWidgets[i];
    if (video==gridWidget)continue;
    gridWidget->showWindow(show);
  }
}

void GridManager::closeVideo(VideoWidget *gridWidget)
{
  //删除视频
  gridWidget->setHasVideo(false);
  for(auto it=_gridWidgets.begin();it!=_gridWidgets.end();it++){
    if(*it!=gridWidget)continue;
    _gridWidgets.erase(it);
    break;
  }
  //清除布局
  QLayoutItem *child;
  while ((child = _gridLayout->takeAt(0)) != nullptr){
    if(child->widget()!=gridWidget)continue;
    delete child;
    delete gridWidget;
    break;
  }
}
VideoWidget* GridManager::getFirstFreeGrid() const
{
  for (int i = 0; i < _gridWidgets.size(); ++i){
    VideoWidget *gridWidget = _gridWidgets[i];
    if (!gridWidget->hasVideo())return gridWidget;
  }
  return nullptr;
}


void GridManager::Relayout(){
  //清除布局
  QLayoutItem *child;
  while ((child = _gridLayout->takeAt(0)) != nullptr){
    delete child;
  }
  //重建  
  int rows = ceil(sqrt(_gridWidgets.size())); 
  for(int row=0;row<rows;row++)
    for(int col=0;col<rows;col++){
      int index=row*rows + col;
      if(index < _gridWidgets.size()){
        VideoWidget *gridWidget = _gridWidgets[index];
        _gridLayout->addWidget(gridWidget, row, col);
      }
    }
}


